package com.swh.ShiroUserRealm;

import com.swh.entity.SysUser;
import com.swh.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: swh
 * @Description:
 * @Date: 2021/1/5 15:26
 * @Version: 1.0
 */
@Component
public class ShiroUserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
//        char[] password = (char[]) token.getCredentials();
//        System.out.println("前端传来的用户名" + username);
//        System.out.println("前端传来的密码" + Arrays.toString(password));

        SysUser sysUser = sysUserService.findByName(username);

        if (sysUser == null) {
            return null;
        }

        ActiverUser activeUser = new ActiverUser(sysUser, null, null);



        /**
         * 参数1 用户身份
         * 参数2 用户在数据库里面存放的密码
         * 参数3 当前类名
         */
        ByteSource bytes = ByteSource.Util.bytes(sysUser.getUsername());
//        System.out.println(bytes);
//        System.out.println(sysUser.getUsername());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, sysUser.getPassword(), bytes, this.getClass().getSimpleName());
        return info;

    }

    /**
     * 授权
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        ActiverUser activeUser = (ActiverUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        List<String> roles = activeUser.getRoles();
        if (null != roles && roles.size() > 0) {
            //添加角色
            info.addRoles(roles);
        }

        List<String> permissions = activeUser.getPermissions();
        if (null != permissions && permissions.size() > 0) {
            //添加角色
            info.addStringPermissions(roles);
        }
        return info;
    }



}
